package com.itheima.reggie.controller;

import com.itheima.reggie.AddressService;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
public class AddressController {
    @Autowired
    private HttpSession httpSession;

    @Autowired
    private AddressService addressService;
    //查询地址普
    @GetMapping("/address/list")
    public ResultInfo findBy(){
       List<Address>addressList= addressService.findBy();
       return ResultInfo.success(addressList);
    }

    //保存地址
    @PostMapping("/address")
    public ResultInfo save(@RequestBody Address address){
        addressService.save(address);
        return ResultInfo.success(null);
    }

    //修改默认
    @PutMapping("/address/default")
    public ResultInfo setDefault(@RequestBody Map<String, Long> map) {
        //1. 接收参数 地址id
        Long id = map.get("id");

        //2. 调用service设置
        addressService.find(id);

        //3. 返回结果
        return ResultInfo.success(null);
    }

    //结算
    @GetMapping("/address/default")
    public ResultInfo js(){
       Address address= addressService.js();
       if (address==null){
           return ResultInfo.error("没有默认地址");
       }else {
           return ResultInfo.success(address);
       }
    }

    //回显地址
    @GetMapping("/address/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
       Address address= addressService.findById(id);
       return ResultInfo.success(address);
    }

    //删除地址
    @DeleteMapping("/address")
    public ResultInfo deleted(Long ids){
        addressService.deleted(ids);
        return ResultInfo.success(null);
    }

    //修改地址
    @PutMapping("/address")
    public ResultInfo put(@RequestBody Address address){
        addressService.put(address);
       return ResultInfo.success(null);
    }

    //推出
    @PostMapping("/user/logout")
    public ResultInfo tuichu(){
        httpSession.invalidate();
        return ResultInfo.success(null);
    }

}
